﻿<!DOCTYPE html>
<html>
<head>
    <title>JS Arrays Exercise 5</title>
    <link href="styles/js-console.css" rel="stylesheet" />
</head>
<body>
    <h1>Sort an array. Use the 'selection sort' algorithm</h1>
    <label for="arr-input">Array:</label>
    <input type="text" id="arr-input" />
    <button onclick="execute()">Execute</button>
    <div id="js-console"></div>
    <script src="scripts/js-console.js"></script>
    <script>
        function execute()
        {
            var arr_string = jsConsole.read("#arr-input");
            var val = arr_string.split(", ");

            // sorted_idx indicates part of the array that is already stored
            for (var sorted_idx = 0; sorted_idx < val.length - 1; sorted_idx++)
            {
                var smallest_index = sorted_idx;
                // Find the smallest element in not sorted part of the array
                for (var idx = sorted_idx + 1; idx < val.length; idx++)
                {
                    if (val[idx] < val[smallest_index])
                    {
                        smallest_index = idx;
                    }
                }
                    
                // Exchange smallest element with first element of not sorted array part
                var tmp_val = val[sorted_idx];
                val[sorted_idx] = val[smallest_index];
                val[smallest_index] = tmp_val;
            }

            jsConsole.writeLine(val.join(", "));
        }
    </script>
</body>
</html>
